package ru.dcsearch.indexer;

/***************************************************************************
 *   Created by TMC
 *   berechitai@gmail.com
 *
 *   This file is part of DC Indexer project
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 ***************************************************************************/

public class PortsPool {

    int[] portsPool;
    int[] statusesPool;


    public PortsPool(Prefs p) {

        
            int beginPort = p.getP2PPort(0);
            int portCount = p.getMaxActiveConnections();

            portsPool = new int[portCount];
            statusesPool = new int[portCount];

            for (int i=0;i< portCount; i++) {


                 portsPool[i] = beginPort + i;
                 statusesPool[i] = 0;

            }

    }

    synchronized public boolean freePortExists() {

        for (int i=0; i<portsPool.length; i++) {

              if (statusesPool[i] == 0) {

                  return true;

              }

        }

        return false;
    }


    synchronized public int lockPort()  {

        for (int i=0; i<portsPool.length; i++) {

              if (statusesPool[i] == 0) {

                  statusesPool[i] = 1;
                  return portsPool[i];

              }

        }

        return 0;

    }

    synchronized public void unlockPort(int port) {

          for (int i=0; i<portsPool.length; i++) {

              if (portsPool[i] == port) {

                  statusesPool[i] = 0;
                  return;

              }

        }

    }

}
